package com.elitesland.security;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.elitesland.core.util.RequestUtil;
import lombok.val;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import static com.elitesland.security.filter.PreLoginFilter.LOGIN_CAPTCHA_KEY;
import static com.elitesland.security.filter.PreLoginFilter.LOGIN_CAPTCHA_UID;
import static org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_PASSWORD_KEY;
import static org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_USERNAME_KEY;

/**
 * <pre>
 * JSON格式登录信息处理器
 * </pre>
 *
 * @author Mir
 * @date 2020/6/16
 */
public class JsonLoginProcessor implements LoginPostProcessor {

    private static ThreadLocal<String> passwordThreadLocal = new ThreadLocal<>();
    private static ThreadLocal<String> captchaThreadLocal = new ThreadLocal<>();
    private static ThreadLocal<String> capuidThreadLocal = new ThreadLocal<>();

    @Override
    public LoginTypeEnum getLoginType() {
        return LoginTypeEnum.JSON;
    }

    @Override
    public String obtainsUsername(ServletRequest request) {
        val requestWrapper = new HttpServletRequestWrapper((HttpServletRequest) request);
        val body = RequestUtil.obtainBody(requestWrapper);
        JSONObject jsonObj = JSONUtil.parseObj(body);
        passwordThreadLocal.set(jsonObj.getStr(SPRING_SECURITY_FORM_PASSWORD_KEY));
        captchaThreadLocal.set(jsonObj.getStr(LOGIN_CAPTCHA_KEY));
        capuidThreadLocal.set(jsonObj.getStr(LOGIN_CAPTCHA_UID));

        return jsonObj.getStr(SPRING_SECURITY_FORM_USERNAME_KEY);
    }

    @Override
    public String obtainPassword(ServletRequest request) {
        val password = passwordThreadLocal.get();
        passwordThreadLocal.remove();
        return password;
    }

    @Override
    public String obtainCaptcha(ServletRequest request) {
        val captcha = captchaThreadLocal.get();
        captchaThreadLocal.remove();
        return captcha;
    }

    @Override
    public String obtainCapUid(ServletRequest request) {
        val capUid = capuidThreadLocal.get();
        capuidThreadLocal.remove();
        return capUid;
    }
}
